<template>
  <div class="lg-container" v-wechat-title="$route.meta.title" v-if="isTemplate">
    <van-cell-group>
      <van-field v-model="data.name" required clearable label="姓名:" placeholder="请输入姓名" />
      <div class="van-cell van-cell--required van-field">
        <div class="van-cell__title van-field__label">
          <span>性别:</span>
        </div>
        <div class="van-cell__value">
          <van-radio-group class="lg-radio-group" v-model="data.sex" @change="sexChange">
            <van-radio
              checked-color="#03A9AC"
              v-for="item in sexList"
              :key="item.key"
              :name="item.key"
            >{{item.valueCn}}</van-radio>
          </van-radio-group>
        </div>
      </div>
      <van-field
        v-model="data.birthday"
        required
        readonly
        label="出生日期:"
        @click="birthdayClick"
        placeholder="请选择出生日期"
      />
      <van-field v-model="data.phone" required clearable label="手机号:" placeholder="请输入手机号" />
      <van-field
        v-model="data.code"
        center
        required
        clearable
        label="验证码"
        placeholder="请输入验证码"
      >
        <van-button slot="button" size="small" type="primary" :disabled="isPhone" @click="onSend" color="#03A9AC">{{sendTitle}}</van-button>
      </van-field>
    </van-cell-group>
    <van-button type="primary" class="lg-patientInfo-btn" @click="onSave" color="#03A9AC">确认</van-button>
    <van-popup v-model="isShow" position="bottom" :style="{ height: '40%' }">
      <van-datetime-picker
        v-model="currentDate"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onBirthdayConfirm"
        @cancel="onCancel"
        type="date"
      />
    </van-popup>
  </div>
</template>
<script>
import { getAllDicByType } from '@/api/common'
import { createOrUpdateInfo, readInfo, sendCode, verificationCode } from '@/api/info'
export default {
  data () {
    return {
      data: {
        openId: '',
        name: '',
        birthday: '',
        sex: '',
        sexShow: '',
        phone: ''
      },
      code: '',
      isPhone: false,
      sendTitle: '发送验证码',
      time: 60,
      currentDate: new Date(),
      maxDate: new Date(),
      minDate: new Date(1900, 0, 1),
      sexList: [],
      isShow: false,
      isTemplate: false,
      parameter: null
    }
  },
  created () {
    if (this.$route.query.openId) {
      this.data.openId = this.$route.query.openId
      this.parameter = this.$route.query.parameter
      this.getInfo()
    }
  },
  methods: {
    getInfo () {
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        overlay: true,
        duration: 0
      })
      readInfo(this.data.openId).then(res => {
        this.$toast.clear()
        if (res.code === 200) {
          switch (res.status) {
            case '1':
              this.isTemplate = true
              this.getAllDicByType()
              break
            case '2':
              setTimeout(() => {
                this.$router.push('/establishStatus?openId=' + this.data.openId)
              }, 1000)
              break
            case '3':
              this.$dialog.confirm({
                title: '提示',
                message: '您已绑定医生，请前往',
                confirmButtonText: '我的信息',
                cancelButtonText: '我的医生',
                cancelButtonColor: '#03A9AC',
                confirmButtonColor: '#03A9AC'
              }).then(() => {
                this.$router.push('/patientInfo?openId=' + this.data.openId)
              }).catch(() => {
                this.$router.push('/doctorInfo?openId=' + this.data.openId)
              })
              break
            default:
              this.$dialog.confirm({
                title: '提示',
                message: '您已绑定医生，请前往',
                confirmButtonText: '我的信息',
                cancelButtonText: '我的医生',
                cancelButtonColor: '#03A9AC',
                confirmButtonColor: '#03A9AC'
              }).then(() => {
                this.$router.push('/patientInfo?openId=' + this.data.openId)
              }).catch(() => {
                this.$router.push('/doctorInfo?openId=' + this.data.openId)
              })
              break
          }
        }
      })
    },
    getAllDicByType () {
      getAllDicByType('sex').then(res => {
        if (res.code === 200) {
          this.sexList = res.list
        }
      })
    },
    sexChange (val) {
      this.data.sexShow = this.sexList.filter(v => {
        return v.key === this.data.sex
      })[0].valueCn
    },
    // 出生日期
    birthdayClick () {
      this.isShow = true
      if (this.data.birthday) {
        this.currentDate = this.data.birthday
      } else {
        this.currentDate = new Date()
      }
      this.showText = 'birthday'
    },
    // 出生日期
    onBirthdayConfirm (val) {
      this.data.birthday = this.parseTime(val, '{y}-{m}-{d}')
      this.isShow = false
    },
    onCancel () {
      this.isShow = false
    },
    onSend () {
      if (this.data.phone === '') {
        this.$toast('请输入手机号')
        return false
      }
      const phoneReg = /^1[0-9]{10,10}$/
      if (!phoneReg.test(this.data.phone)) {
        this.$toast('请输入正确的手机号')
        return false
      }
      sendCode(this.data.phone).then(res => {
        if (res.code === 200) {
          this.$toast('发送成功')
          this.onsetTimeout()
        } else {
          this.$toast(res.msg)
        }
      })
    },
    onsetTimeout () {
      if (this.time === 0) {
        this.isPhone = false
        this.sendTitle = '发送验证码'
        this.time = 60
      } else {
        this.isPhone = true
        this.sendTitle = '重新发送(' + this.time + ')'
        this.time--
        setTimeout(() => {
          this.onsetTimeout()
        }, 1000)
      }
    },
    onSave () {
      const formdata = Object.assign({}, this.data)
      formdata.parameter = this.parameter
      let isOK = true
      let errmsg = ''
      const formRules = [
        { name: 'name', errmsg: '请输入姓名' },
        { name: 'sexShow', errmsg: '请选择性别' },
        { name: 'birthday', errmsg: '请选择出生日期' },
        { name: 'phone', errmsg: '请输入手机号' },
        { name: 'code', errmsg: '请输入短信验证码' }
      ]
      formRules.forEach(v => {
        if (isOK) {
          if (!formdata[v.name] || formdata[v.name] === '') {
            isOK = false
            errmsg = v.errmsg
          }
        }
      })
      if (!isOK) {
        this.$toast(errmsg)
        return false
      }
      const phoneReg = /^1[0-9]{10,10}$/
      if (!phoneReg.test(formdata.phone)) {
        this.$toast('请输入正确的手机号')
        return false
      }
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        overlay: true,
        duration: 0
      })
      new Promise((resolve, reject) => {
        const data = {
          code: this.data.code,
          phone: this.data.phone
        }
        verificationCode(data).then(res => {
          if (res.code === 200) {
            resolve(true)
          } else {
            this.$toast(res.msg)
            resolve(false)
          }
        })
      }).then((val) => {
        if (val) {
          createOrUpdateInfo(formdata).then(res => {
            this.$toast.clear()
            if (res.code === 200) {
              this.$router.push('/status')
            } else {
              this.$toast(res.msg)
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="scss">
.van-picker__cancel,
.van-picker__confirm {
  color: #03a9ac;
}
.lg-radio-group {
  display: flex;
  align-items: center;
  .van-radio {
    margin-right: 15px;
  }
}
.lg-van-cell-group {
  padding: 10px;
}
.lg-type-checkbox {
  padding: 20px;
  box-sizing: border-box;
  .van-checkbox {
    margin-bottom: 10px;
  }
}
.lg-patientInfo-btn {
  width: 90%;
  margin: 20px 5%;
}
</style>
<style lang="scss" scoped>
.lg-container {
  width: 100vw;
  min-height: 100vh;
  background-color: #f4f4f4;
}
</style>
